/*
 * Copyright 2007 National Bioinformatics Network
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dgbgui.command;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;


public class GroupCommand implements Command {

    public GroupCommand() {
        // Use a linked hash set since order is important
        m_commands = new LinkedList<Command>();
    }
    
    public void add(Command command) {
        m_commands.add(command);
    }
    
    public void execute() {
        assert ( m_commands.size() > 0 );
        for ( Command command : m_commands ) {
            command.execute();
        }

    }

    public void undo() {
        // Undo the commands in REVERSE order
        assert ( m_commands.size() > 0 );
        // TODO: Fix the reverse iteration 
        List<Command> reversedList = new LinkedList<Command>(m_commands);
        Collections.reverse(reversedList);
        for ( Command command : reversedList ) {
            command.undo();
        }

    }
    
    public void redo() {
        assert ( m_commands.size() > 0 );
        for ( Command command : m_commands ) {
            command.redo();
        }
    }
    
    
    /**
     * A group command is undable if any of the commands it contains are
     * undoable
     */
    public boolean isUndoable() {
        assert ( m_commands.size() > 0 );
        for ( Command command : m_commands ) {
            if ( command.isUndoable() ) {
                return true;
            }
        }
        return false;
    }
    
    public int size() {
        return m_commands.size();
    }
    
    private List<Command> m_commands;

}
